﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Data.Sql;
using System.Data;
using System.Data.SqlClient;


public partial class SetOrder : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            setDish();
        }
    }
    private void setDish()
    {
        
        HttpCookie usr = Request.Cookies["usr"];
        string account = usr.Value;
        int level =0;
        double vipPrice = 0;
        if (Request.Cookies["ShoppingCart"] == null)
        {
            //如果Cookies中不存在ShoppingCart，则创建
            TableRow row = new TableRow();
            TableCell cell = new TableCell();
            Label lab = new Label();
            lab.Text = "购物车为空";
            cell = new TableCell();
            cell.Width = new Unit(100);
            cell.Controls.Add(lab);
            row.Cells.Add(cell);
            CardTable.Rows.Add(row);
        }
        else
        {
            //增加表名
            TableRow nrow = new TableRow();

            AddCell(nrow,"菜式");
            AddCell(nrow, "单价");
            AddCell(nrow, "数目");
            AddCell(nrow, "合计");
            CardTable.Rows.Add(nrow);

            double sumPrice = 0;


            for (int i = 0; i < Request.Cookies["ShoppingCart"].Values.Count; ++i)
            {
                TableRow row = new TableRow();

                double price  = 0;
                string name = null;
                int num;
                string Dno;

                //得到数据
                Dno = Server.HtmlEncode(Request.Cookies["ShoppingCart"].Values.AllKeys[i]);
                num = int.Parse(Server.HtmlEncode(Request.Cookies["ShoppingCart"].Values[i]));

                if (Dno == null)
                {
                    AddCell(row, "购物车为空");
                    CardTable.Rows.Add(row);
                    break;
                }

                getDishName(Dno, ref name, ref price);
                if (num == 0)
                    continue;

                AddCell(row, name);
                AddCell(row, price.ToString());
                AddCell(row, "×" + num.ToString());
                AddCell(row, (num * price).ToString());

                CardTable.Rows.Add(row);
                sumPrice += num * price ;
            }
            nrow = new TableRow();
            AddCell(nrow,"");
            AddCell(nrow,"");
            AddCell(nrow, "总计");
            AddCell(nrow, sumPrice.ToString() + "￥");            
            level = getVip(account);
            AddCell(nrow, level.ToString()+"级会员价");            
            vipPrice = sumPrice *(1- 0.05 *level);
            AddCell(nrow, vipPrice.ToString()+"￥");
            CardTable.Rows.Add(nrow);
            fullFillTex();
        }      
    }

    private void AddCell( TableRow row, string str)
    {
        TableCell cell = new TableCell();
        Label lab = new Label();
        lab.Text = str;
        cell.Width = new Unit(100);
        cell.Controls.Add(lab);
        row.Cells.Add(cell);
    }

    private void getDishName(string no,ref string  name , ref double price)
    {

        string connectionString = WebConfigurationManager.ConnectionStrings["ConnectionStrCustomer"].ConnectionString;

        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            try
            {
                conn.Open();

                String sqlString = "select * from Customer_Dish where Dno = @no";
                SqlParameter[] parameters = { new SqlParameter("@no",no) };
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = sqlString;
                    cmd.Parameters.AddRange(parameters);
                    SqlDataReader dr = cmd.ExecuteReader();
                    dr.Read();

                    price = double.Parse(dr["Dprice"].ToString());
                    name = dr["Dname"].ToString();
                }


            }
            catch (Exception ez)
            {
                Response.Write(@"<b>异常信息:</b>" + ez.Message);
            }
            finally
            {
                conn.Close();
            }

        }
    }
    protected void SetBut_Click(object sender, EventArgs e)
    {
        setOrder();
    }
    private void setOrder()
    {
        string Ono = null;
        string name = NameTex.Text;
        string tel = TelTex.Text;
        string adr = AdrTex.Text;
        string remark = RemarkTex.Text;
        string payway = PaywayRadioList.SelectedValue;
        string account;
        double sum =0;
        HttpCookie usr = Request.Cookies["usr"];
        account = usr.Value;

        if (checkData(name, tel, adr, remark) == false)
        {
            Response.Write(@"<script>alert('信息填写不符合要求！');</script>");
            return;
        }

        string connectionString = WebConfigurationManager.ConnectionStrings["ConnectionStrCustomer"].ConnectionString;
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            try
            {
                conn.Open();
                //String sqlString = "select * from Customer_Account where Aaccount = @username";
                //得到可用的One 而且是随机的。
                getOno(ref Ono ,conn);

                SqlTransaction trans = conn.BeginTransaction();
                //插入Order
                Ono = insertOrder(conn, Ono, tel, payway, name, adr, trans);
        
                //插入Set_order
                insertSet_order(conn,Ono,account,remark,trans);
                
                double tempSum = 0;
                //插入Choose
                if (insertChoose(conn, Ono, trans,ref tempSum) == true)
                {

                    updateOrder(conn,Ono,trans,tempSum);

                    trans.Commit();//提交事务
                    HttpCookie hc = new System.Web.HttpCookie("ShoppingCart");
                    Response.Cookies.Add(hc);
                    Response.Redirect("./Thanks.aspx");
                    
                }
                else
                {
                    trans.Rollback();
                    Response.Write(@"<script>alert('下订了已售罄的菜式');</script>");
                }

            }
            catch (Exception ez)
            {
                Response.Write(@"<b>异常信息:</b>" + ez.Message);
            }
            finally
            {
                conn.Close();
            }
        }
    }
    private bool checkData( string name , string tel , string adr , string remark )
    {
        bool ans = true;

        if (name.Length > 10)
            ans = false;
        else if (tel.Length > 11)
            ans = false;
        else if (adr.Length > 100)
            ans = false;
        else if (remark.Length > 200)
            ans = false;
        return ans;
    }
    private void getOno(ref string Ono, SqlConnection conn)
    {
        Random ran = new Random();
        long temp = ran.Next(1,100000000);
        while(true)
        {
            temp = ran.Next(1, 100000000);
            Ono = temp.ToString();
            String sqlString = "select Ono from Customer_Order where Ono = @Ono";

            SqlParameter[] parameters = { 
                                                new SqlParameter("@Ono", Ono),
                                            };

            using (SqlCommand cmd = conn.CreateCommand())
            {
                cmd.CommandText = sqlString;
                cmd.Parameters.AddRange(parameters);
                DataSet ds = new DataSet();
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                adapter.Fill(ds);
                DataTable table = ds.Tables[0];
                if (table.Rows.Count > 0)
                {
                    //存在
                }
                else
                { //不存在
                    break;
                }
            }
        }
        return;
    }
    private string insertOrder(SqlConnection conn, string Ono, string Ophone, string Opayway, string Oname, string Oadr, SqlTransaction trans )
    {
        string sqlString = "insert into Customer_Order (Ono , Ophone , Opayway,Oname , Oadr) values(@Ono , @Ophone , @Opayway,@Oname , @Oadr )";

        SqlParameter[] parameters = { 
                                                new SqlParameter("@Ono", Ono),
                                                new SqlParameter("@Ophone", Ophone),
                                                new SqlParameter("@Opayway", Opayway),
                                                new SqlParameter("@Oname", Oname),
                                                new SqlParameter("@Oadr", Oadr),
                                            };
        using (SqlCommand cmd = conn.CreateCommand())
        {
            cmd.Transaction = trans;
            cmd.CommandText = sqlString;
            cmd.Parameters.AddRange(parameters);
            int ret = cmd.ExecuteNonQuery();
            if (ret > 0)
            {
            }
            else
            {
                Response.Write(@"<script>alert('下订失败');</script>");
            }
        }
        return Ono;
    }
    private bool insertSet_order(SqlConnection conn, string Ono, string Aaccount,  string remarks, SqlTransaction trans)
    {
        string sqlString = "insert into Customer_Set_order (Ono , Aaccount , SOtime , SOremarks) values(@Ono , @Aaccount ,  getdate(), @remarks )";

        SqlParameter[] parameters = { 
                                                new SqlParameter("@Ono", Ono),
                                                new SqlParameter("@Aaccount", Aaccount),
                                                new SqlParameter("@remarks", remarks)
                                            };
        using (SqlCommand cmd = conn.CreateCommand())
        {
            cmd.Transaction = trans;
            cmd.CommandText = sqlString;
            cmd.Parameters.AddRange(parameters);
            int ret = cmd.ExecuteNonQuery();
            if (ret > 0)
            {
            }
            else
            {
                Response.Write(@"<script>alert('下订失败');</script>");
                return false;
            }
        }
        return true;
    }
    private bool insertChoose(SqlConnection conn, string Ono, SqlTransaction trans, ref double sum)
    {
        Dictionary<string, Dictionary<int, string>> dict = new Dictionary<string, Dictionary<int, string>>();
        getDnoDict(dict);
        double price;
        foreach (var item in dict)
        {
            string Dno = item.Key;
            int num = 0;
            string remarks ;
            Dictionary<int, string> temp = item.Value;
            foreach(var nitem in temp)
            {
                num = nitem.Key;
                remarks = nitem.Value;
            }
            int storeNum = 0;
            //判断是否有库存
            String sqlString = "select Dprice ,Dstore from Customer_Dish where Dno = @Dno";
            SqlParameter[] parameters = { new SqlParameter("@Dno", Dno) };
            using (SqlCommand cmd = conn.CreateCommand())
            {
                cmd.Transaction = trans;
                cmd.CommandText = sqlString;
                cmd.Parameters.AddRange(parameters);
                SqlDataReader dr = cmd.ExecuteReader();
                dr.Read();
                storeNum = int.Parse(dr["Dstore"].ToString());
                price = double.Parse(dr["Dprice"].ToString());
                dr.Close();
            }
            if( storeNum < num )
            {
                Response.Write(@"<script>alert('"+Dno+"号菜式已售罄"+"');</script>");
                return false;  
            }
            sum += price * num;
            //插入Choose表

            sqlString = "insert into Customer_Choose (Ono , Dno , Cnum ) values(@Ono , @Dno , @Cnum)";

            SqlParameter[] newParameters = { 
                                                new SqlParameter("@Ono", Ono),
                                                new SqlParameter("@Dno", Dno),
                                                new SqlParameter("@Cnum", num)
                                            };
            using (SqlCommand cmd = conn.CreateCommand())
            {
                cmd.Transaction = trans;
                cmd.CommandText = sqlString;
                cmd.Parameters.AddRange(newParameters);
                int ret = cmd.ExecuteNonQuery();
                if (ret > 0)
                {
                }
                else
                {
                    Response.Write(@"<script>alert('下订失败');</script>");
                    return false;
                }
            }
        }
        return true;
    }
    private  void  getDnoDict(Dictionary<string,Dictionary<int, string >> dict)
    {
        for (int i = 0; i < Request.Cookies["ShoppingCart"].Values.Count; ++i)
        {
            int num;
            string Dno;
            string remarks = "haha";
            Dictionary<int,string> temp = new Dictionary<int,string>();
            //得到数据
            Dno = Server.HtmlEncode(Request.Cookies["ShoppingCart"].Values.AllKeys[i]);
            num = int.Parse(Server.HtmlEncode(Request.Cookies["ShoppingCart"].Values[i]));
            if (num <= 0)
                continue;
            temp[num] = remarks;
            dict[Dno] = temp;
        }
    }
    private void fullFillTex()
    {
        string connectionString = WebConfigurationManager.ConnectionStrings["ConnectionStrCustomer"].ConnectionString;
        string account;
        HttpCookie usr = Request.Cookies["usr"];
        account = usr.Value;
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            try
            {
                conn.Open();

                String sqlString = "select * from Customer_Account where Aaccount = @username";
                SqlParameter[] parameters = { new SqlParameter("@username", account) };
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = sqlString;
                    cmd.Parameters.AddRange(parameters);
                    SqlDataReader dr = cmd.ExecuteReader();
                    dr.Read();

                    NameTex.Text = dr["Aname"].ToString();
                    TelTex.Text = long.Parse(dr["Atel"].ToString()).ToString();
                    AdrTex.Text = dr["Aadr"].ToString();
                    RemarkTex.Text = dr["Aref"].ToString();
                    dr.Close();
                }

            }
            catch (Exception ez)
            {
                Response.Write(@"<b>异常信息:</b>" + ez.Message);
            }
            finally
            {
                conn.Close();
            }
        }

    }
    private void updateOrder(SqlConnection conn,string Ono, SqlTransaction trans, double sum)
    {
        string sqlString = "update Customer_ViewOrderHist set Osumprice = @Osumprice where Ono = @Ono ";

        SqlParameter[] parameters = { 
                                                new SqlParameter("@Ono", Ono),
                                                new SqlParameter("@Osumprice", sum)
                                            };
        using (SqlCommand cmd = conn.CreateCommand())
        {
            cmd.Transaction = trans;
            cmd.CommandText = sqlString;
            cmd.Parameters.AddRange(parameters);
            int ret = cmd.ExecuteNonQuery();
            if (ret > 0)
            {
            }
            else
            {
                Response.Write(@"<script>alert('下订失败');</script>");
                return ;
            }
        }
        return ;
    }
    private int getVip(string account )
    {
        string connectionString = WebConfigurationManager.ConnectionStrings["ConnectionStrCustomer"].ConnectionString;
        int level = 0;
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            try
            {
                conn.Open();

                String sqlString = "select AvipLel from Customer_Account where Aaccount = @Aaccount";
                SqlParameter[] parameters = { new SqlParameter("@Aaccount", account) };
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = sqlString;
                    cmd.Parameters.AddRange(parameters);
                    SqlDataReader dr = cmd.ExecuteReader();
                    dr.Read();
                    level = int.Parse(dr["AvipLel"].ToString());
                }

            }
            catch (Exception ez)
            {
                Response.Write(@"<b>异常信息:</b>" + ez.Message);
            }
            finally
            {
                conn.Close();
            }
        }
        return level;
    }    
}